<template>
  <div class="app-container">

    <CustomContent>
      <template v-slot:body>
        <div id="mmv-page" v-loading="loading">
          <MmvTitle title="方案信息"></MmvTitle>
          <el-form size="mini" label-width="130px" ref="form">

            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="方案名称" prop="charteredBusPlanName" class="is-required">
                  <el-input
                    v-model="charteredBusPlanName"
                    placeholder="请输入">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="所属车型" required v-if="charteredBusPlanId">
                  <el-input :value="modelInfo" disabled style="width:100%" placeholder="品牌车系车型"></el-input>
                </el-form-item>
                <el-form-item label="选择车型" required v-else>
                  <el-input :value="modelInfo" readonly style="width:100%" placeholder="品牌车系车型" @click.native="showchexing=true">
                    <el-button slot="append" icon="el-icon-search" @click="showchexing=true"></el-button>
                  </el-input>
                  <el-dialog title="品牌车系车型" :visible.sync="showchexing" width="900px" append-to-body>
                    <el-row :gutter="10" class="mb10">
                      <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddModel" v-hasPermi="['order:orderBasic:add']">从车型库选择</el-button>
                      </el-col>
                    </el-row>
                    <el-table :data="configurationList" border>
                      <el-table-column label="品牌车系" prop="modelInfo"></el-table-column>
                      <el-table-column label="车型" prop="modelName"></el-table-column>
                      <el-table-column label="所属门店" prop="storeName"></el-table-column>
                      <el-table-column label="操作">
                        <template slot-scope="{row}">
                          <el-button type="text" @click="checkModel(row)">选择</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <pagination v-show="modeltotal>0" :total="modeltotal" :page.sync="configurationquery.pageNum" :limit.sync="configurationquery.pageSize" @pagination="getConfigurationList"/>
                  </el-dialog>

                  <el-dialog title="从车型库选择" :visible.sync="showAddModel" width="1000px" append-to-body @close="closeModelForm">
                    <el-form ref="modelForm" :model="modelForm"  :rules="rules" label-width="140px">
                      <el-row>
                        <el-col :span="24">
                          <div style="font-size: 20px">车型信息</div>
                          <el-form-item label="归属门店" prop="storeId" >
                            <el-select v-model="modelForm.storeId" placeholder="请选择归属门店" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in storeList" :key="item.storeId" :label="item.storeName" :value="item.storeId"></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="所属品牌" prop="carBrandId" >
                            <el-select v-model="modelForm.carBrandId" placeholder="请选择所属品牌" @change="getSeriesList" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in brandList" :key="item.brandId" :label="item.brandName" :value="item.brandId"></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="所属车系" prop="carSeriesId" >
                            <el-select v-model="modelForm.carSeriesId" placeholder="请选择所属车系" @change="getAllModelList" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in seriesList" :key="item.seriesId" :label="item.seriesName" :value="item.seriesId"></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="车型名称" prop="modelId" >
                            <el-select v-model="modelForm.modelId" placeholder="请选择所属车型" @change="checkNewModel" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in allModelList" :key="item.id" :label="item.modelName" :value="item.id"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <div style="font-size: 20px">其他信息</div>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="车辆类型" prop="styleModel">
                              <el-select v-model="modelForm.styleModel" placeholder="请选择车辆类型" class="el-input-style">
                                <el-option v-for="dict in dict.type.style_model" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="变速箱" prop="speedChangingBox">
                              <el-select v-model="modelForm.speedChangingBox" placeholder="请选择变速箱" class="el-input-style">
                                <el-option v-for="dict in dict.type.speed_changing_box" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="燃油类型" prop="fuelType">
                              <el-select v-model="modelForm.fuelType" placeholder="请选择燃油类型" class="el-input-style">
                                <el-option v-for="dict in dict.type.fuel_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="排量" prop="displacement">
                              <el-select v-model="modelForm.displacement" placeholder="请选择排量" class="el-input-style">
                                <el-option v-for="dict in dict.type.displacement" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <el-form-item label="座位数" prop="seating">
                            <div class="grid-content bg-purple">
                              <el-select v-model="modelForm.seating" placeholder="请选择座位" class="el-input-style">
                                <el-option v-for="dict in dict.type.seat" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </div>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                      <el-button type="primary" :loading="addLoading" @click="addModelFormr">确 定</el-button>
                      <el-button @click="closeModelForm">取 消</el-button>
                    </div>
                  </el-dialog>

                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15" v-if="modelInfo != null">
              <el-col :span="8">
                <el-form-item label="所属门店" prop="storeName" >
                  <el-input
                    readonly
                    v-model="storeName"
                    placeholder="自动带出">
                     >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15" >
              <el-col :span="8">
                <el-form-item label="用车时间类型" prop="useTimeType"  class="is-required">
                  <el-radio-group v-model="useTimeType">
                    <el-radio
                      v-for="dict in dict.type.use_time_type"
                      :key="dict.value"
                      :label="parseInt(dict.value)"
                    >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15" v-if="2==useTimeType">
              <el-col :span="8">
                <el-form-item label="公里数" prop="kilometers" class="is-required">
                  <el-input
                    v-model="kilometers"
                    placeholder="请输入"
                    @keyup.native="kilometers = oninput(kilometers,2)"
                    @blur="kilometers = oninput(kilometers,2)"
                    clearable
                    style="width:200px">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15" v-if="2==useTimeType">
              <el-col :span="8">
                <el-form-item label="用车时间" prop="setUseTimes" class="is-required">

                  <el-input-number v-model="setUseTimes" :precision="0" :min="1" :max="24" label=""></el-input-number>

<!--                  <el-input-->
<!--                    v-model="setUseTimes"-->
<!--                    placeholder="请输入"-->
<!--                    @keyup.native="setUseTimes = oninput(setUseTimes,2)"-->
<!--                    @blur="setUseTimes = oninput(setUseTimes,2)"-->
<!--                    clearable-->
<!--                    style="width:200px">-->
<!--                  </el-input>-->
                  小时
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="车辆押金" prop="deposit" class="is-required">
                  <el-input
                    v-model="deposit"
                    placeholder="请输入"
                    @keyup.native="deposit = oninput(deposit,2)"
                    @blur="deposit = oninput(deposit,2)"
                    clearable
                    style="width:200px">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="车辆租金" prop="deposit" class="is-required">
                  <el-input
                    v-model="rent"
                    placeholder="请输入"
                    @keyup.native="rent = oninput(rent,2)"
                    @blur="rent = oninput(rent,2)"
                    clearable
                    style="width:200px">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>

          <MmvTitle title="收费信息"  v-if="1==useTimeType || 2==useTimeType">
            <span slot="btn" class="addFeeItem" @click="handleBindFeeItem">添加收费项</span>
          </MmvTitle>
          <el-row :gutter="15"  v-if="1==useTimeType || 2==useTimeType">
            <el-col :span="24">
            <el-table :data="feeItemList" stripe :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border>
              <template slot="empty">
                <el-empty :image-size="50" description="暂无其他收费项"></el-empty>
              </template>
              <el-table-column label="费用项名称" align="center" prop="feeItemName" />
              <el-table-column label="费用项金额" align="center" prop="feeItemValue" />
              <el-table-column label="费用类型" align="center" prop="chargeItemsType">
                <template v-slot="{ row }">
                  <el-tag v-if="row.chargeItemsType == 1">次</el-tag>
                  <el-tag v-else-if="row.chargeItemsType == 2">天</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
                <template v-slot="scope">
                  <el-button size="small" type="text" @click="handleUnBindFeeItem(scope.$index, scope.row)">删除</el-button>

                </template>
              </el-table-column>
            </el-table>

            </el-col>
          </el-row>



        </div>
      </template>
      <template v-slot:footer>
        <div class="footer">
          <el-button type="primary" @click.native="saveForm" :loading="addPlanLoading">保存</el-button>
          <el-button type="info" plain @click.native="close">取消</el-button>
        </div>
      </template>
    </CustomContent>

    <bind-feeItem ref="bindFeeItem" @success="addFeeItemSuccess"></bind-feeItem>
  </div>



</template>

<script>
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import * as planApi from "@/api/plan/plan";
import map from 'lodash/map';
import forEach from 'lodash/forEach';
import MmvTable from './components/mmv-table.vue'
import * as Utils from '@/utils'
import {
  listBasic
} from "@/api/car/car_basic";
import {tenantlist} from "@/api";
import CustomContent from "@/components/custom/content";

import {insertCharteredBusPlan, updateCharteredBusPlan} from "@/api/charteredBus/priceSetting";

import cloneDeep from 'lodash/cloneDeep';
import {getCarBrandList, getCarModelList, getCarSeriesList, getStoreList ,insertModelBuss} from "@/api/car/model";
import {addInsurance, updateInsurance} from "@/api/maintenance/insurance";
import bindFeeItem from './components/bindFeeItem.vue';
import * as charteredBusPlanApi from "@/api/charteredBus/priceSetting";
export default {
  components: {
    MmvTitle,
    MmvTable,
    CustomContent,
    bindFeeItem,
  },
  dicts: [
    'use_time_type',
    'style_model', 'speed_changing_box', 'displacement', 'fuel_type','seat'
  ],
  data() {
    return {
      feeItemList: [],
      charteredBusItemsBillingList:[],
      addFeeItem: false,
      deviceIdList: [],
      modelForm: {
        carBrandId: null,
        carSeriesId: null,
        modelId: null,
      },
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: '归属门店不能为空', trigger: 'blur' },
        ],
        carBrandId: [
          { required: true, message: '所属品牌不能为空', trigger: 'blur' },
        ],
        carSeriesId: [
          { required: true, message: '所属车系不能为空', trigger: 'blur' },
        ],
        modelId: [
          { required: true, message: '车型不能为空', trigger: 'blur' },
        ],
      },
      brandList: [],
      storeList: [],
      seriesList: [],
      allModelList: [],
      modelList: [],
      // 总条数
      total: 0,
      drawerFlag: false,
      addPlanLoading: false,
      direction: 'rtl',
      tenantId: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        carNo: null,
      },
      modeltotal: 0,
      modelloading: false,
      deposit: 0,
      useTimeType:1,
      storeName:null,
      charteredBusPlanName:null,
      rent: 0,
      kilometers:0,
      setUseTimes:1,
      weeksPrice: 0, // 周内价格
      weekendPrice: 0, // 周末价格
      //
      prevEdit: null,
      nowPrice: 0,
      nowEdit: null,
      loading: false,
      showchexing: false,
      showAddModel: false,
      addLoading: false,
      title: '',
      planName: '', // 车价名称
      //
      configurationId: '', // 品牌车系车型
      modelId: '',
      modelName: '',
      modelInfo: '',
      upcoverImage: '',
      detailsImage: [],
      //
      label: [],
      operatingClassification: "",
      //
      isSetMeal: 2, // 是否需要套餐车价
      // 是否显示弹出层
      open: false,
      openkehu: false, // 客户选择弹窗
      value: new Date(),
      list: [{
        mondayPrice: 0,
        tuesdayPrice: 0,
        wednesdayPrice: 0,
        thursdayPrice: 0,
        fridayPrice: 0,
        saturdayPrice: 0,
        sundayPrice: 0,
      }],
      checktable: [{}],
      checktableindex: 0,
      checklistteshutable: [{}],
      checklistteshutableindex: 0,
      radio: 0,
      chargeInsureList: [], // 保险项
      configurationList: [], // 车型业务配置列表
      configurationquery: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        configurationId: null
      },
      tenantConfig: {
        illegalDeposit: 0,
        pageSinightServiceFeeze: 2,
        nightServiceFeeStart: null,
        nightServiceFeeEnd: null,
        nightServiceFeePrice: null,
        nightServiceFeeRemark: null
      },
    }
  },
  computed: {
    isEdit() {
      return !!this.form.charteredBusPlanId;
    },
    rilijiage() {
      return {
        0: this.list[0].sundayPrice,
        1: this.list[0].mondayPrice,
        2: this.list[0].tuesdayPrice,
        3: this.list[0].wednesdayPrice,
        4: this.list[0].thursdayPrice,
        5: this.list[0].fridayPrice,
        6: this.list[0].saturdayPrice,
      }
    },
    submitFormData() {
      return {
        charteredBusPlanId: this.charteredBusPlanId, // 包车方案ID
        configurationId: this.configurationId,
        charteredBusPlanName: this.charteredBusPlanName, // 包车方案ID
        operatingClassification: this.operatingClassification,
        deposit: this.deposit,
        rent:this.rent,
        kilometers:this.kilometers,
        setUseTimes:this.setUseTimes,
        useTimeType:this.useTimeType,
        charteredBusItemsBillingList: this.feeItemList, // 费用项
      }
    },
  },
  watch: {
  },
  async mounted() {
    this.loading = true;
    await this.getTenantConfig(); // 获取租户配置
    this.loading = false;
    this.charteredBusPlanId = this.$route.query.charteredBusPlanId;
    this.storeName = this.$route.query.storeName;
    console.log("带过来的charteredBusPlanId：",this.charteredBusPlanId)
    if (this.charteredBusPlanId) {
      console.log('走修改流程');
      await this.getData();
    } else {
    }
    await this.getConfigurationList(); // 获取车型业务配置列表
  },
  methods: {

    clickItemRow(row) {
      this.$refs.itemTable.toggleRowSelection(row)
    },
    clickInsureRow(row) {
      this.$refs.insureTable.toggleRowSelection(row)
    },
    //新增设备
    addFeeItemSuccess(item) {
      this.feeItemList.push(item);
    },
    handleUnBindFeeItem(index, row) {
      this.$confirm('确定删除该费用项目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.feeItemList.splice(index, 1)
      }).catch(() => {

      });

    },
    // 绑定费用项显示弹框
    handleBindFeeItem() {
      console.log('列表绑定的费用项>>>', this.feeItemList);
      this.$refs.bindFeeItem.show(this.feeItemList);
    },
    saveForm() {
      const form = this.submitForm()

      this.form = cloneDeep(form)
      console.log("提交的数据：",this.form);
      if (this.form.charteredBusPlanId != undefined && this.form.charteredBusPlanId != null  && this.form.charteredBusPlanId != '' ) {
        this.addPlanLoading = true
        updateCharteredBusPlan(this.form)
          .then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.close()
          })
          .catch((err) => {
            this.addPlanLoading = false
          })
      } else {
        this.addPlanLoading = true
        insertCharteredBusPlan(this.form)
          .then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.close()
          })
          .catch((err) => {
            this.addPlanLoading = false
          })
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getModelList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDrivingLicenseValidityDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    modelInventory() {
      this.drawerFlag = true;
      this.title = "车辆库存:" + this.modelInfo
      this.getModelList();
    },
    getModelList() {
      this.modelloading = true;
      this.queryParams.carModelId = this.modelId
      listBasic(this.queryParams).then(response => {
        this.modelList = response.rows;
        this.total = response.total;
        this.modelloading = false;
      });
    },
    handleClose(done) {
      done();
    },
    handleAddModel() {
      this.clearModelForm();
      getCarBrandList().then((response) => {
        this.brandList = response.data
      })

      getStoreList().then((response) => {
        this.storeList = response.data
      })
      this.showAddModel = true
    },
    checkModel(row) {
      this.showchexing = false;
      this.configurationId = row.configurationId;
      this.modelId = row.modelId;
      this.modelName = row.modelInfo;
      this.modelInfo = row.modelInfo+' '+row.modelName;
      this.storeName = row.storeName;
      this.operatingClassification = "";
    },

    isShowEdit(data, date) {
      return data.isSelected && this.nowEdit == date.getTime();
      // return data.isSelected && this.nowEdit != date.getTime();
    },
    okEdit(date) {
      this.nowEdit = null;
      this.prevEdit = date.getTime();
      // this.nowEdit = date.getTime();
      if (!this.nowPrice) return;
      this.addTeshuri(this.nowPrice, date, date);
    },

    /** 获取车型业务配置列表 */
    async getConfigurationList() {
      const result = await charteredBusPlanApi.configurationList(this.configurationquery);
      this.configurationList = result.rows || [];
      this.modeltotal = result.total
    },
    /** 获取租户配置 */
    async getTenantConfig() {
      const result = await planApi.getTenantConfig();
      this.tenantConfig = result.data;
    },

    close() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    submitForm() {
      return this.submitFormData;
    },
    // 获取车系
    getSeriesList(carBrandId) {
      this.modelForm.carSeriesId = null
      this.modelForm.modelId = null
      this.seriesList = []
      this.allModelList = []
      getCarSeriesList(carBrandId).then((response) => {
        this.seriesList = response.data
      })
    },
    // 获取车型
    getAllModelList() {
      this.modelForm.modelId = null
      this.allModelList = []
      getCarModelList(this.modelForm.carSeriesId).then((response) => {
        this.allModelList = response.data
      })
    },
    checkNewModel(){
      let newModel=this.allModelList.filter(item=>{
        return item.id === this.modelForm.modelId
      })[0]
      this.modelForm.styleModel = newModel.styleModel
      this.modelForm.speedChangingBox = newModel.speedChangingBox
      this.modelForm.fuelType = newModel.fuelType
      this.modelForm.displacement = newModel.displacement
      this.modelForm.seating = newModel.seating
      this.modelForm.modelName = newModel.modelName
      this.modelForm.modelInfo = newModel.carBrandName+" "+ newModel.carSeriesName
    },
    closeModelForm(){
      this.showAddModel = false;
      this.clearModelForm();
      this.getConfigurationList();
    },
    clearModelForm(){
      this.modelForm={
        carBrandId: null,
        carSeriesId: null,
        modelId: null,
        styleModel: null,
        speedChangingBox: null,
        fuelType: null,
        displacement: null,
        seating: null
      }
    },
    addModelFormr(){
      this.$refs["modelForm"]?.validate(valid => {
        if (valid) {
          if(!this.modelForm.storeId){
            this.$modal.msgError('未选择门店')
          }else if(!this.modelForm.modelId){
            this.$modal.msgError('未选择车型')
          }else{
            this.addLoading = true;
            insertModelBuss(this.modelForm)
              .then((response) => {
                this.$modal.msgSuccess('添加成功')
                this.closeModelForm()
                this.addLoading = false
                this.checkModel(response.data)
              })
              .catch((err) => {
                this.addLoading = false
              })
          }
        }
      });
    },
    async getData() {
      console.log("进来的计划好：",this.charteredBusPlanId)
      this.loading = true;
      await charteredBusPlanApi.getInfo(this.charteredBusPlanId).then(response => {
        this.configurationId = response.data.configurationId;
        this.operatingClassification = response.data.operatingClassification;
        this.modelId = response.data.modelId;
        this.deposit = response.data.deposit;
        this.modelInfo = response.data.modelInfo;
        this.rent = response.data.rent;
        this.kilometers =  response.data.kilometers;
        this.setUseTimes =  response.data.setUseTimes;
        this.useTimeType =  response.data.useTimeType;
        this.charteredBusPlanName = response.data.charteredBusPlanName;
        this.tenantId = response.data.tenantId;
        this.modelName = response.data.modelName
        this.feeItemList = response.data.charteredBusItemsBillingList;
        // 还原节假日/特殊日价格
        this.loading = false;
      });

    },
    /** */
  },
}
</script>

<style>
#mmv-page .next {
  background: #f5f5f5;
}

#mmv-page .prev {
  background: #f5f5f5;
}

#mmv-page .el-calendar-day {
  padding: 0;
}

#mmv-page .next .rili-price-wrap {
  display: flex;
  align-items: center;
  padding: 5px 5px 0;
  color: #999;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  justify-content: center;
  white-space: nowrap;
}

.el-tooltip__popper {
  max-width: 500px;
}
</style>

<style lang="scss" scoped>
#mmv-page {

::v-deep .el-calendar-table .el-calendar-day {
  height: 60px;
}

}
.rili {
  width: 100%;
  height: 100%;
  font-size: 12px;
}

.rili-wrap {
  position: relative;
}

.el-icon-refresh-left {
  position: absolute;
  top: 8px;
  right: 8px;
}

.aaaaaa {
  background: rgb(253, 226, 226);
}

.rili-day {
  color: #999;
}

.rili-price-wrap {
  display: flex;
  align-items: center;
  padding: 5px 5px 0;
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  justify-content: center;
  white-space: nowrap;

}


.addFeeItem {
  position: relative;
  font-size: 14px;
  top: 8px;
  color: #5473E8;
}
</style>

